#define _CRT_SECURE_NO_WARNINGS 1

#include "SingleList.h"

void SLPrint(SLN* psl)
{
    assert(psl != NULL);

    while (psl != NULL)
    {
        printf("%d ", psl->val);
        psl = psl->next;
    }
    printf("\n");
}

SLN* BuyNewNode(SLDT val)
{
    SLN* newnode = (SLN*)malloc(sizeof(SLN));
    if (newnode == NULL)
    {
        perror("malloc failed");
        return NULL;
    }

    newnode->val = val;
    newnode->next = NULL;

    return newnode;
}

void SLPushFront(SLN** pphead, SLDT val)
{
    SLN* newnode = BuyNewNode(val);
    if (newnode == NULL)
    {
        return;
    }

    newnode->next = *pphead;
    *pphead = newnode;
}

void SLPushBack(SLN** pphead, SLDT val)
{
    assert(pphead);

    SLN* newnode = BuyNewNode(val);
    if (newnode == NULL)
    {
        perror("malloc failed");
        return;
    }

    if (*pphead == NULL)
    {
        *pphead = newnode;
        return;
    }

    SLN* cur = *pphead;

    while (cur->next)
    {
        cur = cur->next;
    }

    cur->next = newnode;
}

void SLPopFront(SLN** pphead)
{
    assert(pphead);
    assert(*pphead);

    SLN* del = *pphead;
    *pphead = (*pphead)->next;
    free(del);
}

void SLPopBack(SLN** pphead)
{
    assert(pphead);
    assert(*pphead);

    if ((*pphead)->next == NULL)
    {
        free(*pphead);
        *pphead = NULL;
        return;
    }

    SLN* tail = *pphead;

    while (tail->next->next)
    {
        tail = tail->next;
    }

    free(tail->next);
    tail->next = NULL;
}

SLN* SLFind(SLN* phead, SLDT val)
{
    assert(phead);

    SLN* cur = phead;
    while (cur != NULL)
    {
        if (cur->val == val)
        {
            return cur;
        }
    }

    return NULL;
}

void SLInsert(SLN** pphead, SLN* pos, SLDT val)
{
    assert(pphead);

    if (*pphead == pos)
    {
        SLPushFront(pphead, val);
        return;
    }

    SLN* prev = *pphead;
    while (prev->next != pos)
    {
        prev = prev->next;
    }

    SLN* newnode = BuyNewNode(val);
    prev->next = newnode;
    newnode->next = pos;
}

void SLErase(SLN** pphead, SLN* pos)
{

}

void SLDestroy(SLN** pphead)
{
    assert(pphead);

    SLN* cur = *pphead;

    while (cur)
    {
        SLN* next = cur->next;
        free(cur);
        cur = next;
    }
}